package com.xihuanjun.util.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author: 江溪浣
 * @createDate: 2022/10/18 11:42
 * @description:
 */
public class JSONUtils {

    public static String jsonToString(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String jsonToStringIgnoreNull(Object o) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T stringToObj(String jsonString, Class<T> clazz) {
        if (StringUtils.hasText(jsonString)) {
            ObjectMapper mapper = new ObjectMapper();
            T t = null;
            try {
                t = mapper.readValue(jsonString, clazz);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return t;
        }
        return null;
    }

    public static Map stringToMap(String jsonString)  {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> tmpMap= null;
        try {
            tmpMap = mapper.readValue(jsonString, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return tmpMap;
    }
}
